﻿package com.wly.box2d
{
	import flash.geom.Point;
	
	import Box2D.Collision.b2Manifold;
	import Box2D.Collision.b2WorldManifold;
	import Box2D.Dynamics.b2ContactListener;
	import Box2D.Dynamics.b2Fixture;
	import Box2D.Dynamics.b2World;
	import Box2D.Dynamics.Contacts.b2Contact;
	
	public class B2CollistionListener extends b2ContactListener
	{
		private var _boxWorld:b2World;
		
		public function B2CollistionListener(world:b2World)
		{
			super();
			
			_boxWorld = world;
		}
		
		override public function BeginContact(contact:b2Contact):void
		{
			var fixtureA:b2Fixture = contact.GetFixtureA();
			var fixtureB:b2Fixture = contact.GetFixtureB();
			
			var itemA:BoxItem = fixtureA.GetBody().GetUserData() as BoxItem;
			var itemB:BoxItem = fixtureB.GetBody().GetUserData() as BoxItem;
			
			//var worldManifold:b2Manifold = contact.GetManifold();
			
			var worldManifold:b2WorldManifold = new b2WorldManifold();
			contact.GetWorldManifold(worldManifold);
			//trace(this, "BeginContact", worldManifold.m_points[0].x*Box2dDefine.PIXEL_PER_METER, worldManifold.m_points[0].y*Box2dDefine.PIXEL_PER_METER);
			var pos:Point = new Point(worldManifold.m_points[0].x*Box2dDefine.PIXEL_PER_METER, worldManifold.m_points[0].y*Box2dDefine.PIXEL_PER_METER);
			
			if(itemA && itemB)
			{
				if(!_boxWorld)
				{
					return;
				}
				if(!itemA.onHit(itemB.viewObj, pos))
				{
					itemA.boxBody.SetUserData(Box2dDefine.BOX_ITEM_DATA_REMOVE);
				}
				
				if(!itemB.onHit(itemA.viewObj, pos))
				{
					itemB.boxBody.SetUserData(Box2dDefine.BOX_ITEM_DATA_REMOVE);
				}
			}
		}
	}
}